package com.zcily.demo.controller;

import com.zcily.demo.config.RabbitConfig;
import com.zcily.demo.entity.dto.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/rabbitmq")
@Slf4j
@Api(tags = "RabbitMQ测试")
public class RabbitMQController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/sendCommonMessage")
    @ApiOperation(value = "发送普通消息")
    public Result<Object> sendCommonMessage(@RequestParam("message") String message) {
        MessageProperties messageProperties = new MessageProperties();
        Message messageObj = new Message(message.getBytes(), messageProperties);
        rabbitTemplate.send(RabbitConfig.COMMON_EXCHANGE, RabbitConfig.COMMON_ROUTINGKEY, messageObj);
        log.info(" 发送一条信息给队列common.queue:{}", message);
        return Result.ok();
    }

    @GetMapping("/sendDelayedMessage")
    @ApiOperation(value = "发送延迟消息")
    public Result<Object> sendDelayedMessage(
            @RequestParam("message") String message,
            @RequestParam("delay") Integer delay) {
//        rabbitTemplate.convertAndSend(RabbitConfig.DELAYED_EXCHANGE_NAME, RabbitConfig.DELAYED_ROUTING_KEY, message,
//                correlationData -> {
//                    correlationData.getMessageProperties().setDelay(delay);
//                    return correlationData;
//                });
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setDelay(delay);  // 设置延迟时间（毫秒）
        Message messageObj = new Message(message.getBytes(), messageProperties);
        rabbitTemplate.send(RabbitConfig.DELAYED_EXCHANGE, RabbitConfig.DELAYED_ROUTINGKEY, messageObj);  // 发送消息到延时交换机

        log.info(" 发送一条延迟{}毫秒的信息给队列delayed.queue:{}", delay, message);
        return Result.ok();
    }
}
